package com.jimo.basetools.utils;

import java.io.UnsupportedEncodingException;
import java.util.Base64;

/**
 * <p>Title: Base64Utils</p>
 * <p>Description:</p> 
 * @author JIMO
 * @date 2019年8月2日
 */
public class Base64Utils {

    /**
     * 
     * Title: encode
     * Description: Base64编码
     * @param s source data
     * @param format Encoding format
     * @return 返回编码后的字符串
     */
    public static String encode(String s, String format) {
        Base64.Encoder encoder = Base64.getEncoder();
        try {
            byte[] b = s.getBytes(format);
            String encodedStr = encoder.encodeToString(b);
            return encodedStr;
        } catch (Exception e) {
            return null;
        }
        
    }
    
    /**
     * 
     * Title: encode
     * Description: Base64编码，默认为utf-8
     * @param s 源数据
     * @return 返回编码后的字符串
     */
    public static String encode(String s) {
        return encode(s, "UTF-8");
    }
    
    /**
     * 
     * Title: encode
     * Description: Base64编码
     * @param b 源数据byte
     * @return 返回编码后的字符串
     */
    public static String encode(byte[] b) {
        Base64.Encoder encoder = Base64.getEncoder();
        return encoder.encodeToString(b);
    }
    
    /**
     * 
     * Title: encodeToByte
     * Description: Base64编码
     * @param b 源数据byte
     * @return 返回编码后的byte
     */
    public static byte[] encodeToByte(byte[] b) {
        Base64.Encoder encoder = Base64.getEncoder();
        return encoder.encode(b);
    }
    
    /**
     * 
     * Title: decode
     * Description: Base64解码
     * @param s 源数据
     * @param format 编码格式
     * @return 返回解码后的字符串
     */
    public static String decode(String s, String format) {
        Base64.Decoder decoder = Base64.getDecoder();
        try {
            return new String(decoder.decode(s), format);
        } catch (UnsupportedEncodingException e) {
            return null;
        }
    }
    
    /**
     * 
     * Title: decode
     * Description: Base64解码，默认为utf-8
     * @param s 源数据
     * @return 返回解码后的字符串
     */
    public static String decode(String s) {
        return decode(s, "UTF-8");
    }
    
    /**
     * 
     * Title: decode
     * Description: Base64解码
     * @param b 源数据byte
     * @return 返回解码后的字符串
     */
    public static String decode(byte[] b) {
        Base64.Decoder decoder = Base64.getDecoder();
        return new String(decoder.decode(b));
    }
    
    /**
     * 
     * Title: decoderToByte
     * Description: Base64解码
     * @param b 源数据byte
     * @return 返回解码后的byte
     */
    public static byte[] decoderToByte(byte[] b) {
        Base64.Decoder decoder = Base64.getDecoder();
        return decoder.decode(b);
    }
    
}
